package com.fortune.cat.resource;

import com.fortune.cat.builder.CookieBuilder;
import com.fortune.cat.config.LoginFilter;
import com.fortune.cat.jooq.tables.pojos.TbUser;
import com.fortune.cat.service.UserService;
import com.fortune.cat.vo.FortuneCatResult;
import org.jooq.DSLContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zhaozeyang
 * @date 2019/5/7 15:32
 * @description
 */
@RestController
@RequestMapping("/fortune/cat/user")
public class UserResource {

    private final com.fortune.cat.jooq.tables.TbUser tbUser = com.fortune.cat.jooq.tables.TbUser.TB_USER;

    private final DSLContext dsl;

    public UserResource(DSLContext dsl) {
        this.dsl = dsl;
    }

    @PostMapping("/login")
    private ResponseEntity<FortuneCatResult> loginIn(@RequestBody TbUser User) {
        List<TbUser> users = dsl.select().from(tbUser)
                .where(tbUser.USER_NAME.eq(User.getUserName()))
                .fetchInto(TbUser.class);
        if (CollectionUtils.isEmpty(users)) {
            return ResponseEntity.ok(FortuneCatResult.error("no user"));
        }
        HttpHeaders headers = new HttpHeaders();

        if (!users.get(0).getPassWord().equals(User.getPassWord())) {
            return ResponseEntity.ok(FortuneCatResult.error("password error"));
        }
        //设置cookie
        String cookie = new CookieBuilder().setKey(LoginFilter.USER_ID)
                .setValue(users.get(0).getId().toString())
                .setMaxAge(60 * 2 * 60 * 1000)
                .setPath("/")
                .build();
        headers.add("Set-Cookie", cookie);
        return new ResponseEntity<>(FortuneCatResult.success(), headers, HttpStatus.OK);
    }

    @GetMapping("/person")
    public Mono<FortuneCatResult> person() {
        return Mono.just(FortuneCatResult.success(UserService.currentUser().getUserName()));
    }
}
